package com.jthinker.client.utils;

import com.caucho.hessian.client.HessianProxyFactory;
import com.jthinker.bean.UserWrapper;
import com.jthinker.service.TicketService;
import com.migcomponents.migbase64.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import static com.jthinker.base.constant.Constant.*;

/**
 * Created by chen.gang on 2015/1/16.
 */
public class SSOClientUtils
{
    private static final Logger LOGGER = LoggerFactory.getLogger(SSOClientUtils.class);

    private static final ReadProperties PROPS = new ReadProperties("/sso.properties");

    private static final String SSO_SERVER = PROPS.getValue("server");
    private static final String VALIDATE_URL = PROPS.getValue("url");
    private static final String API_VALIDATE = PROPS.getValue("api_validate");

    private static final String SSO_VALIDATE_URL = "http://" + SSO_SERVER + VALIDATE_URL;

    //票据校验URL
    private static final String SSO_API_VALIDATE = "http://" + SSO_SERVER + API_VALIDATE;

    private static final HessianProxyFactory FACTORY = new HessianProxyFactory();

    //过滤的URL
    private static final Set<String> ESCAPE_URLS = new HashSet<String>();

    public static final ConcurrentMap<String, HttpSession> GLOBAL_USERS = new ConcurrentHashMap<String, HttpSession>();

    static
    {
        String str = PROPS.getValue("escape_urls");
        String[] arr = StringUtils.split(str, ";");

        for (String url : arr)
        {
            ESCAPE_URLS.add(url);
        }
    }

    /**
     * 校验票据
     *
     * @param st
     * @return
     */
    public static UserWrapper validateST(String st)
    {
        try
        {
            TicketService ticketService = (TicketService) FACTORY.create(TicketService.class, SSO_API_VALIDATE);
            return ticketService.validateST(st);
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
            LOGGER.error("Exception: {}", e);
        }
        return null;
    }

    /**
     * 跳转到ssoServer
     *
     * @param request
     * @param response
     * @throws IOException
     */
    public static void redirectToSSOServer(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        String url = request.getRequestURL().toString();
        String service = Base64.encodeToString(url.getBytes(DEFAULT_CHARSET), false);

        StringBuilder redirectUrl = new StringBuilder();
        redirectUrl.append(SSO_VALIDATE_URL).append("?").append(SERVICE_NAME).append("=").append(service);

        response.sendRedirect(redirectUrl.toString());
    }

    /**
     * 判断是不是要PASS的URL
     *
     * @param url
     * @return
     */
    public static boolean isEscapeUrl(String url)
    {
        AntPathMatcher pathMatcher = AntPathMatcher.getInstance();

        for (String pattern : ESCAPE_URLS)
        {
            if (pathMatcher.match(pattern, url))
            {
                return true;
            }
        }

        return false;
    }

    /**
     * 取SSOUser
     *
     * @param request
     * @return
     */
    public static final UserWrapper getSSOUser(HttpServletRequest request)
    {
        return (UserWrapper) request.getSession().getAttribute(SSO_SESSION);
    }

    /**
     * SSO本地登录
     *
     * @param request
     * @param st
     * @param userWrapper
     */
    public static void login(HttpServletRequest request, String st, UserWrapper userWrapper)
    {
        HttpSession session = request.getSession();
        session.setAttribute(SSO_SESSION, userWrapper);
        GLOBAL_USERS.put(st, session);
    }

    /**
     * SSO本地登出
     *
     * @param st
     * @return
     */
    public static boolean logout(String st)
    {
        HttpSession session = GLOBAL_USERS.remove(st);
        if (session != null)
        {
            session.invalidate();
            return true;
        }
        else
        {
            return false;
        }

    }
}
